package com.home.free.controller.pdf;

import com.home.free.controller.BaseController;
import com.home.free.controller.pdf.query.PdfSplitQuery;
import com.home.free.util.PdfUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author gaotianjie
 */
@Controller
@RequestMapping("/pdf")
public class PdfController extends BaseController {
    @RequestMapping(value = "/split", method = RequestMethod.GET)
    public ModelAndView split (Model model) {
        model.addAttribute("name", "世界你好");
        ModelAndView mav = new ModelAndView();
        mav.setViewName("pdf/split");
        return mav;
    }

    @RequestMapping(value = "/split", method = RequestMethod.POST)
    @ResponseBody
    public void postSplit(PdfSplitQuery pdfSplit, HttpServletResponse res, HttpServletRequest request) throws IOException {
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("pdfFile");
        if (file == null) {
            throw new RuntimeException("对象不能为空");
        }

        long currentTimeMillis = System.currentTimeMillis();

        String fileName = currentTimeMillis + ".pdf";

        String s = "/var/logs/free/pdf/" + fileName;

        FileOutputStream fileOutputStream = new FileOutputStream(s);

        PdfUtil.splitPDF(file.getInputStream(), fileOutputStream, pdfSplit.getStartPage(), pdfSplit.getEndPage());

        download(res, s);
    }

    private void download (HttpServletResponse response, String path) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();

            file.delete();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
